package com.jiukuaidao.library.util;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;

import com.jiukuaidao.library.Config;

/**
 * Author : PaiTaSuo
 * Date : 2016/5/25
 * Description :
 */
public class ToastUtil {

    /**
     * 系统原生类型
     **/
    private static final int SYSTYPE = 1;

    private static Context mContext = Config.mContext;
    private static Handler mHandler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SYSTYPE:
                    if (msg.obj != null && msg.obj instanceof ToastBean) {
                        ToastBean bean = (ToastBean) msg.obj;
                        Toast.makeText(mContext, bean.text, bean.duration).show();
                    }
                    break;
            }
        }
    };

    /**
     * 系统原生Toast
     *
     * @param text
     * @param duration
     */
    public static void show(String text, int duration) {
        if (Looper.myLooper() != Looper.getMainLooper()) {// 非主线程
            ToastBean bean = new ToastUtil.ToastBean();
            bean.text = text;
            bean.duration = duration;
            Message msg = Message.obtain();
            msg.what = SYSTYPE;
            msg.obj = bean;
            mHandler.sendMessage(msg);
        } else {
            Toast.makeText(mContext, text, duration).show();
        }
    }

    /**
     * 系统原生Toast
     *
     * @param textId
     * @param duration
     */
    public static void show(int textId, int duration) {
        String text = mContext.getResources().getString(textId);
        show(text, duration);
    }

    static class ToastBean {
        private String text;
        private int duration;
    }
}
